package socket.handler;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Comparator;

import org.springframework.beans.factory.annotation.Autowired;

import exception.BadDataException;

import service.ServerMediator;

import com.tntgroup.sudokuonline.message.Message;

public class ServerSocketHandler implements SocketHandler,Comparable<ServerSocketHandler> {
	private long id;
	private Socket socket;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private ServerMediator mediator;
	
	public ServerSocketHandler(Socket socket, ObjectInputStream in,
			ObjectOutputStream out, ServerMediator mediator) {
		super();
		this.socket = socket;
		this.in = in;
		this.out = out;
		this.mediator = mediator;
	}
	
	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	@Override
	public Message readSocket() throws BadDataException {
		// TODO Auto-generated method stub
		Message message=null;
		if(!socket.isClosed()){
			try {
				message = (Message) in.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		else{
			throw new BadDataException("socket is closed");
		}
		return message;
	}
	@Override
	public void writeSocket(Message message) throws BadDataException {
		// TODO Auto-generated method stub
		if(!socket.isClosed()){
			try {
				out.writeObject(message);
				out.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		else{
			throw new BadDataException("socket is closed");
		}
	}
	@Override
	public void closeSocket() throws IOException {
		// TODO Auto-generated method stub
		in.close();
		out.close();
		socket.close();
	}
	@Override
	public void processMessage(Message message) {
		// TODO Auto-generated method stub
		mediator.analyzeMessage(message,this);
	}

	@Override
	public int compareTo(ServerSocketHandler o) {
		// TODO Auto-generated method stub
		if(id<o.getId()) return -1;
		else if(id==o.getId()) return 0;
		return 1;
	}


}
